package com.iwhalecloud.bss.kite.cucc.service.custview;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.iwhalecloud.bss.hsf.baseinf.service.InfExchangeService;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.SymbolConsts;
import com.iwhalecloud.bss.kite.common.util.KiteDateUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.customerOrderInformation.QryGrpMemberDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.customerOrderInformation.QryGrpMemberListByGrpReq;
import com.iwhalecloud.bss.kite.cucc.client.dto.customerOrderInformation.QryGrpMemberListByMemReq;
import com.iwhalecloud.bss.kite.cucc.client.dto.customerOrderInformation.QryJkAndCbUserDetailInfoReq;
import com.iwhalecloud.bss.kite.cucc.client.dto.customerOrderInformation.QryMemDiscntInfoReq;
import com.iwhalecloud.bss.kite.cucc.client.dto.customerOrderInformation.QryTagInfos;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.ProdInstQryDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.UserQueryDTO;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.CustViewBaseVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.CustViewVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.DiscntInfo;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.Fee;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.Group;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.GroupInfoVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.MemberDto;
import com.iwhalecloud.bss.kite.cucc.common.callclient.HttpsCallClient;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalCallClientEnum;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalInfConsts;
import com.iwhalecloud.bss.kite.cucc.service.attr.LocalAttrHelper;
import com.iwhalecloud.bss.kite.cucc.service.customerOrderInformation.CustomerOrderInfoService;
import com.iwhalecloud.bss.kite.cucc.service.custview.evolve.task.GroupInfoTask;
import com.iwhalecloud.bss.kite.cucc.service.inf.InfServiceHelper;
import com.iwhalecloud.bss.kite.cucc.service.util.LocalTokenUtil;
import com.iwhalecloud.bss.kite.dataservice.cache.AttrValueCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.AttrValue;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;

import com.ztesoft.bss.common.util.PropertiesUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.common.logger.api.ZLogger;
import com.ztesoft.common.logger.factory.ZLoggerFactory;

/**
 * @ClassName : GetGroupInfoTask
 * @Description : 群组信息
 * @Author : xie.zhengjun
 * @Date : 2021/1/23 13:03
 * @deprecated 已停止维护，请勿使用。改进版本解除Callable绑定，干干净净，只专注业务本身。见：{@link GroupInfoTask}
 */
public class GetGroupInfoTask extends CustViewBaseTask {

    private final ZLogger LOGGER = ZLoggerFactory.getLogger(this.getClass(), KeyConsts.LOG_MODULE);

    public GetGroupInfoTask(Object[] args) {
        super(args);
    }

    @Override
    public CustViewBaseVO call() throws Exception {
        Object[] args = getArgs();
        if (args.length != 3) {
            return null;
        }
        //3.3.用户信息查询服务
        // 群组实例标识(GROUP_ID GRP_INFO 群组标识)，
        // 群组类型(GROUP_TYPE_ID GRP_INFO 群组类型ID)，
        // 群组描述(GROUP_DESC GRP_INFO 群组描述)
        Map<String, Object> userDetail = (Map<String, Object>) args[0];
        if (KiteMapUtils.isEmpty(userDetail)) {
            return null;
        }

        CustViewVO custViewVO = (CustViewVO) args[1];
        String accNum = (String) args[2];

        GroupInfoVO groupInfoVO = new GroupInfoVO();
        Group group = new Group();
        groupInfoVO.setGroup(group);
        List<MemberDto> members = new ArrayList<>();
        groupInfoVO.setMembers(members);
        /*FusionMemberUsersDto fusionMemberUsersDto = new FusionMemberUsersDto();
        groupInfoVO.setFusionMemberUsers(fusionMemberUsersDto);*/
        custViewVO.setGroup(groupInfoVO);

        /*
         * 判断查询的集团用户是否是群组用户，根据用户信息查询服务接口USER_DIFF_CODE字段返回2开头代表集团群组关系，
         * 8开头代表融合群组关系；
         * 如果不是群组用户，那么群组信息tab页下面的群组信息和成员信息为空。
         */
        Map<String, Object> userInfo = (Map<String, Object>) userDetail.get("USER_INFO");
        if (KiteMapUtils.isEmpty(userInfo)) {
            return groupInfoVO;
        }

        String userStateCode = Optional.ofNullable(String.valueOf(userInfo.get("SERVICE_STATE_CODE"))).orElse("");
        String userStateCodeDesc = Optional.ofNullable(AttrValueCache.getAttrValue("2020012105", userStateCode))
            .map(AttrValue::getAttrValueName).orElse(userStateCode);

        String userDiffCode = KiteMapUtils.getString(userInfo, "USER_DIFF_CODE");
        if (!userDiffCode.startsWith("8") && !userDiffCode.startsWith("2")) {
            List<Map<String, Object>> userRelationInfos = (List<Map<String, Object>>) userDetail.get("USER_RELATION_INFOS");
            if (KiteListUtils.isNotEmpty(userRelationInfos)) {
                Map<String, Object> userRelationInfo = userRelationInfos.get(0);
                //群组号码
                String primarySerialNumber = KiteMapUtils.getString(userRelationInfo, "PRIMARY_SERIAL_NUMBER");
                //群组标识
                String primaryUserId = KiteMapUtils.getString(userRelationInfo, "PRIMARY_USER_ID");
                //群组类型
                String relationTypeName = KiteMapUtils.getString(userRelationInfo, "RELATION_TYPE_NAME");

                // 成员用户数量（ROW_COUNT RspBody 总条数）
                QryGrpMemberListByGrpReq qryGrpMemberListByGrpReq = new QryGrpMemberListByGrpReq();
                qryGrpMemberListByGrpReq.setPrimarySerialNumber(primarySerialNumber);
                Map memberListByGrp = this.qryGrpMemberListByGrp(qryGrpMemberListByGrpReq);
                Integer rowCount = 0;
                if (KiteMapUtils.isNotEmpty(memberListByGrp)) {
                    Map<String, Object> resultObject = getMemberListByGrp(memberListByGrp);
                    //成员用户数量
                    rowCount = KiteMapUtils.getInteger(resultObject, "ROW_COUNT");
                }

                LOGGER.info("集团业务号码:{}, 群组实例标识:{}, 群组类型:{}, 成员用户数量:{}",
                    primarySerialNumber, primaryUserId, relationTypeName, rowCount);
                /*fusionMemberUsersDto.setPrimarySerialNumber(primarySerialNumber);
                fusionMemberUsersDto.setPrimaryUserId(primaryUserId);
                fusionMemberUsersDto.setRelationTypeName(relationTypeName);
                fusionMemberUsersDto.setRowCount(rowCount);
                fusionMemberUsersDto.setState(userStateCodeDesc);
                fusionMemberUsersDto.setGroupDesc("");*/
                //群组实例标识
                group.setGroupInstId(primaryUserId);
                //集团业务号码
                group.setAccNum(primarySerialNumber);
                //群组描述
                group.setGroupDesc("");
                //群组类型
                group.setGroupType(relationTypeName);
                //状态
                group.setState(userStateCodeDesc);
                //成员用户数量
                group.setMemberCount(KiteStringUtils.valueOf(rowCount));
            }
            return groupInfoVO;
        }

        /*
         * 群组实例标识
         * 集团业务号码
         * 群组描述
         * 群组类型
         * 状态
         */
        //群组实例标识
        group.setGroupInstId("");
        //集团业务号码
        group.setAccNum(accNum);
        //群组描述
        group.setGroupDesc("");
        String userDifeName = KiteMapUtils.getString(userInfo, "USER_DIFF_NAME");
        //群组类型
        group.setGroupType(userDifeName);
        //状态
        group.setState(userStateCodeDesc);


        //3.5.群组查成员列表
        // 成员用户数量（ROW_COUNT RspBody 总条数）
        QryGrpMemberListByGrpReq qryGrpMemberListByGrpReq = new QryGrpMemberListByGrpReq();
        qryGrpMemberListByGrpReq.setPrimarySerialNumber(accNum);
        Map memberListByGrp = this.qryGrpMemberListByGrp(qryGrpMemberListByGrpReq);
        if (KiteMapUtils.isNotEmpty(memberListByGrp)) {
            Map<String, Object> resultObject = getMemberListByGrp(memberListByGrp);

            //成员用户数量
            Integer rowCount = KiteMapUtils.getInteger(resultObject, "ROW_COUNT");
            group.setMemberCount(KiteStringUtils.valueOf(rowCount));

            Map<String, Object> groupMemberListByMap = (Map<String, Object>) resultObject.get("GROUP_MEMBERLIST");

            //获取成员列表
            List<JSONObject> groupMemberList = (List<JSONObject>) groupMemberListByMap.get("GROUP_MEMBERLISTS");
            if (KiteListUtils.isNotEmpty(groupMemberList)) {
                groupMemberList.forEach((groupMember) -> {
                    QryGrpMemberDTO grpMemberDto = JSON.parseObject(groupMember.toJSONString(), QryGrpMemberDTO.class);
                    if (grpMemberDto != null) {
                        //成员号码
                        String memSerialNumber = grpMemberDto.getMemSerialNumber();
                        //成员号码的ID
                        String memUserId = grpMemberDto.getMemUserId();
                        //1 查询政企用户 2 查询公众用户
                        String memSource = grpMemberDto.getMemSource();

                        if (KiteStringUtils.isNotEmpty(memSerialNumber)) {
                            //根据成员号码查出成员详细信息
                            QryGrpMemberListByMemReq qryGrpMemberListByMemReq = new QryGrpMemberListByMemReq();
                            qryGrpMemberListByMemReq.setMemSerialNumber(memSerialNumber);
                            Map MemberListByMem = this.qryGrpMemberListByMem(qryGrpMemberListByMemReq);

                            if (KiteMapUtils.isNotEmpty(MemberListByMem)) {
                                // 成员详细信息
                                // 成员用户号码（MEM_SERIAL_NUMBER GROUP_MEMBERLISTS B号码）
                                // 成员证件号码（MEM_CUST_CERT_CODE GROUP_MEMBERLISTS B归属客户证件号码），
                                // 成员用户名称（MEM_CUST_CERT_TYPE_NAME GROUP_MEMBERLISTS B归属客户证件类别名称），
                                // 成员客户证件（MEM_CUST_CERT_TYPE_CODE GROUP_MEMBERLISTS B归属客户证件类别编码），
                                // 归属地市（MEM_EPARCHY_CODE GROUP_MEMBERLISTS B地市编码，MEM_PROVINCE_CODE GROUP_MEMBERLISTS B省分编码）
                                // 群组生效时间(START_DATE GROUP_MEMBERLISTS 群组关系生效时间)，
                                // 群组失效时间(END_DATE GROUP_MEMBERLISTS 群组关系失效时间)
                                // 状态
                                MemberDto memberDto = this.getMemberDto(MemberListByMem);
                                //归属地市
                                if (KiteStringUtils.isNotEmpty(grpMemberDto.getMemProvinceCode())) {
                                    memberDto.setMemProvinceCode(grpMemberDto.getMemProvinceCode());
                                }
                                String provinceCode = memberDto.getPrimaryProvinceCode();
                                if (KiteStringUtils.isEmpty(provinceCode)) {
                                    provinceCode = memberDto.getMemProvinceCode();
                                }
                                String eparchyCode = memberDto.getPrimaryEparchyCode();
                                if (KiteStringUtils.isEmpty(eparchyCode)) {
                                    eparchyCode = memberDto.getMemEparchyCode();
                                }
                                String cityCode = memberDto.getMemCityCode();
                                String regionValDesc = String.join(SymbolConsts.HYPHEN,
                                    LocalAttrHelper.getRegionName(provinceCode),
                                    LocalAttrHelper.getRegionName(eparchyCode),
                                    LocalAttrHelper.getRegionName(cityCode));
                                memberDto.setMemEparchyName(regionValDesc);

                                //资费信息
                                // 资费编码（DISCNT_CODE	EXTERNAL_USER_DISCNT_INFOS），
                                // 资费名称（DISCNT_NAME	EXTERNAL_USER_DISCNT_INFOS），
                                // 资费描述（DISCNT_DESCRIBE	EXTERNAL_USER_DISCNT_INFOS），
                                // 开始时间（START_DATE	EXTERNAL_USER_DISCNT_INFOS），
                                // 结束时间（END_DATE	EXTERNAL_USER_DISCNT_INFOS）
                                QryJkAndCbUserDetailInfoReq qryJkAndCbUserDetailInfoReq = new QryJkAndCbUserDetailInfoReq();
                                qryJkAndCbUserDetailInfoReq.setUserSource(memSource);
                                qryJkAndCbUserDetailInfoReq.setUserId(memUserId);
                                List<QryTagInfos> qryTagInfosList = new ArrayList<>();
                                QryTagInfos qryTagInfos = new QryTagInfos();
                                qryTagInfos.setTagName("USER_DISCNT");
                                qryTagInfos.setTranslateFlag("1");
                                qryTagInfos.setValidFlag("0");
                                qryTagInfosList.add(qryTagInfos);
                                QryTagInfos qryTagInfos2 = new QryTagInfos();
                                qryTagInfos2.setTagName("USER_DISCNT_ITEM");
                                qryTagInfos2.setTranslateFlag("1");
                                qryTagInfos2.setValidFlag("0");
                                qryTagInfosList.add(qryTagInfos2);
                                qryJkAndCbUserDetailInfoReq.setQryTagInfos(qryTagInfosList);
                                Map map = qryJkAndCbUserDetailInfo(qryJkAndCbUserDetailInfoReq);

                                if (KiteMapUtils.isNotEmpty(map)) {
                                    List<Fee> feeByMember = getFeeByMember(map);
                                    if (KiteListUtils.isNotEmpty(feeByMember)) {
                                        memberDto.setFeeList(feeByMember);
                                    }
                                }

                                members.add(memberDto);
                            }
                        }
                    }
                });
            }
        }

        return groupInfoVO;
    }

    private Map<String, Object> getMemberListByGrp(Map memberListByGrp) {
        Map<String, Object> uniBssBody = (Map<String, Object>) memberListByGrp.get("UNI_BSS_BODY");
        if (KiteMapUtils.isEmpty(uniBssBody)) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("","返回报文缺少UNI_BSS_BODY节点");
        }
        Map<String, Object> rsp = (Map<String, Object>) uniBssBody.get("RSP");
        if (!KiteStringUtils.equals(KiteMapUtils.getString(rsp, "RESULT_CODE"), "0000")) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("",KiteMapUtils.getString(rsp, "RESULT_MSG"));
        }
        Map<String, Object> resultObject = (Map<String, Object>) rsp.get("RESULT_OBJECT");
        if (KiteMapUtils.isEmpty(resultObject)) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("",KiteMapUtils.getString(rsp, "RESULT_MSG"));
        }
        return resultObject;
    }

    private Map qryGrpMemberListByMem(QryGrpMemberListByMemReq qryGrpMemberListByMemReq) {
        String pageNum = KiteStringUtils.valueOf(qryGrpMemberListByMemReq.getCurPage());
        String pageSize = KiteStringUtils.valueOf(qryGrpMemberListByMemReq.getPageSize());
        pageNum = KiteStringUtils.isNotEmpty(pageNum) ? pageNum : "1";
        pageSize = KiteStringUtils.isNotEmpty(pageSize) ? pageSize : "10";
        Integer intpageNum = Integer.parseInt(pageNum);
        Integer intPageSize = Integer.parseInt(pageSize);
        String memSerialNumber = qryGrpMemberListByMemReq.getMemSerialNumber();

        Map<String, Object> req = new HashMap<>();
        req.put("MEM_SERIAL_NUMBER", memSerialNumber);
        req.put("CUR_PAGE", intpageNum);
        req.put("PAGE_SIZE", intPageSize);

        //tcp_cont
        Map<String, String> tcpContMap = new HashMap<String, String>();
        tcpContMap.put("APP_KEY", LocalInfConsts.APP_ID);
        tcpContMap.put("TRANS_ID", LocalTokenUtil.getTransId());
        req.put("TCP_CONT", tcpContMap);

        Map<String, Object> uniBssBody = new HashMap<>();
        uniBssBody.put("REQ", req);

        Map<String, Object> request = new HashMap<>();
        request.put("UNI_BSS_BODY", uniBssBody);
        request.put("OP_CODE", "json_GEuserCenter_SalBusaGrpMemberSerApi_qryGrpMemberListByMem");
        InfServiceHelper.adaptGray(request, req);

        String result;
        String property = PropertiesUtil.getProperty("interface.call.mode");
        if (KiteStringUtils.isEqual(property, "http")) {
            result = HttpsCallClient
                .postStringWithObject(LocalCallClientEnum.INF_COMMON_URL, request, LocalTokenUtil.getHeaderMap());
        } else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            result = infExchangeService.exchange(new JSONObject(request));
        }

        if (KiteStringUtils.isNotEmpty(result)) {
            Map resultMap = JSON.parseObject(result, Map.class);
            if (KiteMapUtils.isNotEmpty(resultMap)) {
                return resultMap;
            } else {
                return null;
            }
        }
        return null;
    }

    private Map qryGrpMemberListByGrp(QryGrpMemberListByGrpReq qryGrpMemberListByGrpReq) {
        Integer pageNum = qryGrpMemberListByGrpReq.getCurPage();
        Integer pageSize = qryGrpMemberListByGrpReq.getPageSize();
        pageNum = pageNum != null ? pageNum : 1;
        pageSize = pageSize != null ? pageSize : 10;
        String primarySerialNumber = qryGrpMemberListByGrpReq.getPrimarySerialNumber();

        Map<String, Object> req = new HashMap<>();
        req.put("PRIMARY_SERIAL_NUMBER", primarySerialNumber);
        req.put("CUR_PAGE", pageNum);
        req.put("PAGE_SIZE", pageSize);

        //tcp_cont
        Map<String, String> tcpContMap = new HashMap<String, String>();
        tcpContMap.put("APP_KEY", LocalInfConsts.APP_ID);
        tcpContMap.put("TRANS_ID", LocalTokenUtil.getTransId());
        req.put("TCP_CONT", tcpContMap);

        Map<String, Object> uniBssBody = new HashMap<>();
        uniBssBody.put("REQ", req);

        Map<String, Object> request = new HashMap<>();
        request.put("UNI_BSS_BODY", uniBssBody);
        request.put("OP_CODE", "json_GEuserCenter_SalBusaGrpMemberSerApi_qryGrpMemberListByGrp");
        InfServiceHelper.adaptGray(request, req);

        String result;
        String property = PropertiesUtil.getProperty("interface.call.mode");
        if (KiteStringUtils.isEqual(property, "http")) {
            result = HttpsCallClient
                .postStringWithObject(LocalCallClientEnum.INF_COMMON_URL, request, LocalTokenUtil.getHeaderMap());
        } else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            result = infExchangeService.exchange(new JSONObject(request));
        }

        if (KiteStringUtils.isNotEmpty(result)) {
            Map resultMap = JSON.parseObject(result, Map.class);
            if (KiteMapUtils.isNotEmpty(resultMap)) {
                return resultMap;
            } else {
                return null;
            }
        }
        return null;
    }

    private MemberDto getMemberDto(Map MemberListByMem) {
        Map<String, Object> uniBssBody = (Map<String, Object>) MemberListByMem.get("UNI_BSS_BODY");
        if (KiteMapUtils.isEmpty(uniBssBody)) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("","返回报文缺少UNI_BSS_BODY节点");
        }
        Map<String, Object> rsp = (Map<String, Object>) uniBssBody.get("RSP");
        if (!KiteStringUtils.equals(KiteMapUtils.getString(rsp, "RESULT_CODE"), "0000")) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("",KiteMapUtils.getString(rsp, "RESULT_MSG"));
        }
        Map<String, Object> resultObject = (Map<String, Object>) rsp.get("RESULT_OBJECT");
        if (KiteMapUtils.isEmpty(resultObject)) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("",KiteMapUtils.getString(rsp, "RESULT_MSG"));
        }

        Map<String, Object> groupMemberListByMap = (Map<String, Object>) resultObject.get("GROUP_MEMBERLIST");

        List<JSONObject> groupMemberList = (List<JSONObject>) groupMemberListByMap.get("GROUP_MEMBERLISTS");
        JSONObject jsonObject = groupMemberList.get(0);
        MemberDto memberDto = null;
        if (!jsonObject.isEmpty()) {
            memberDto = JSON.parseObject(jsonObject.toJSONString(), MemberDto.class);
        }

        return memberDto;
    }

    private ProdInstQryDTO getProdInstQryDTO(String custId, String serialNumberVal,
                                             String provinceCode, String eparchyCode) {
        CustomerOrderInfoService customerOrderInfoService = SpringUtil.getBean(CustomerOrderInfoService.class);
        ProdInstQryDTO prodInstQryDTO = null;
        try {
            Map<String, String> map = new HashMap<>(5);
            map.put("custId", custId);
            map.put("accNum", serialNumberVal);
            map.put("eparchyCode", eparchyCode);
            map.put("provinceCode", provinceCode);
            UserQueryDTO userQueryDTO = customerOrderInfoService.queryUserList(map);
            if (Objects.nonNull(userQueryDTO)) {
                List<ProdInstQryDTO> userList = userQueryDTO.getUserList().getList();
                if (KiteListUtils.isNotEmpty(userList)) {
                    prodInstQryDTO = userList.get(0);
                }
            }
        } catch (Exception e) {
            LOGGER.error(ErrorConsts.SYSTEM_ERROR.getErrorCode(), e, "getProdInstQryDTO");
        }

        return prodInstQryDTO;
    }

    private Map qryMemDiscntInfo(QryMemDiscntInfoReq qryMemDiscntInfoReq) {
        Map<String, Object> uniBssBody = new HashMap<>();
        Map<String, Object> req = new HashMap<>();
        req.put("USER_IDA", qryMemDiscntInfoReq.getUserIda());
        req.put("MEMBER_USER_ID", qryMemDiscntInfoReq.getMemberUserId());
        req.put("STATE_FLAG", qryMemDiscntInfoReq.getStateFlag());
        req.put("STAFF_ID", qryMemDiscntInfoReq.getStaffId());

        uniBssBody.put("REQ", req);
        Map<String, Object> request = new HashMap<>();
        request.put("UNI_BSS_BODY", uniBssBody);
        request.put("OP_CODE", "json_GEuserCenter_UserDiscntServiceApi_qryMemDiscntInfo");
        InfServiceHelper.adaptGray(request, req);

        String result;
        String property = PropertiesUtil.getProperty("interface.call.mode");
        if (KiteStringUtils.isEqual(property, "http")) {
            result = HttpsCallClient
                .postStringWithObject(LocalCallClientEnum.INF_COMMON_URL, request, LocalTokenUtil.getHeaderMap());
        } else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            result = infExchangeService.exchange(new JSONObject(request));
        }

        if (KiteStringUtils.isNotEmpty(result)) {
            return JSON.parseObject(result, Map.class);
        }

        return null;
    }

    private List<DiscntInfo> getDiscntInfo(Map qryMemDiscntInfoReq) {
        Map<String, Object> uniBssBody = (Map<String, Object>) qryMemDiscntInfoReq.get("UNI_BSS_BODY");
        if (KiteMapUtils.isEmpty(uniBssBody)) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("返回报文缺少UNI_BSS_BODY节点");
        }
        Map<String, Object> rsp = (Map<String, Object>) uniBssBody.get("RSP");
        if (!KiteStringUtils.equals(KiteMapUtils.getString(rsp, "RESP_CODE"), "0000")) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("",KiteMapUtils.getString(rsp, "RESULT_MSG"));
        }
        List<JSONObject> data = (List<JSONObject>) rsp.get("DATA");
        if (KiteListUtils.isEmpty(data)) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("",KiteMapUtils.getString(rsp, "RESULT_MSG"));
        }

        JSONObject jsonObject = data.get(0);
        List<DiscntInfo> discntInfos = null;
        if (!jsonObject.isEmpty()) {
            discntInfos = JSON.parseObject(jsonObject.toJSONString(), new TypeReference<List<DiscntInfo>>() {
            });
        }

        return discntInfos;
    }

    /**
     * 查询政企用户与公众用户详情接口
     *
     * @param qryJkAndCbUserDetailInfoReq 查询政企用户与公众用户详情接口入参
     * @return
     */
    private Map qryJkAndCbUserDetailInfo(QryJkAndCbUserDetailInfoReq qryJkAndCbUserDetailInfoReq) {

        String userId = qryJkAndCbUserDetailInfoReq.getUserId();
        String isQryJk = qryJkAndCbUserDetailInfoReq.getIsQryJk();
        String serialNumber = qryJkAndCbUserDetailInfoReq.getSerialNumber();
        String userSource = qryJkAndCbUserDetailInfoReq.getUserSource();
        String provinceCode = qryJkAndCbUserDetailInfoReq.getProvinceCode();
        String eparchyCode = qryJkAndCbUserDetailInfoReq.getEparchyCode();
        String staffCode = qryJkAndCbUserDetailInfoReq.getStaffCode();
        List<QryTagInfos> qryTagInfos = qryJkAndCbUserDetailInfoReq.getQryTagInfos();

        Map<String, Object> req = new HashMap<>();
        req.put("PROVINCE_CODE", provinceCode);
        req.put("EPARCHY_CODE", eparchyCode);
        req.put("STAFF_CODE", staffCode);
        req.put("SERIAL_NUMBER", serialNumber);
        req.put("USER_ID", userId);
        req.put("USER_SOURCE", userSource);
        req.put("IS_QRY_JK", isQryJk);

        Map<String, String> tcpCount = new HashMap<>();
        tcpCount.put("APP_KEY", LocalInfConsts.APP_ID);
        tcpCount.put("TRANS_ID", LocalTokenUtil.getTransId());
        req.put("TCP_CONT", tcpCount);

        List<Map<String, String>> qryTagInfoList = new ArrayList<>();
        for (QryTagInfos qryTagInfo : qryTagInfos) {
            Map<String, String> map = new HashMap<>();
            map.put("TAG_NAME", qryTagInfo.getTagName());
            map.put("VALID_FLAG", qryTagInfo.getValidFlag());
            map.put("TRANSLATE_FLAG", qryTagInfo.getTranslateFlag());
            qryTagInfoList.add(map);
        }
        req.put("QRY_TAG_INFOS", qryTagInfoList);

        Map<String, Object> uniBssBody = new HashMap<>();
        uniBssBody.put("REQ", req);

        Map<String, Object> request = new HashMap<>();
        request.put("UNI_BSS_BODY", uniBssBody);
        request.put("OP_CODE", "json_GEuserCenter_QryUserDetailServiceApi_qryJkAndCbUserDetailInfo");
        InfServiceHelper.adaptGray(request, req);

        String result;
        String property = PropertiesUtil.getProperty("interface.call.mode");
        if (KiteStringUtils.isEqual(property, "http")) {
            result = HttpsCallClient
                .postStringWithObject(LocalCallClientEnum.INF_COMMON_URL, request, LocalTokenUtil.getHeaderMap());
        } else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            result = infExchangeService.exchange(new JSONObject(request));
        }

        if (KiteStringUtils.isNotEmpty(result)) {
            Map resultMap = JSON.parseObject(result, Map.class);
            if (KiteMapUtils.isNotEmpty(resultMap)) {
                return resultMap;
            } else {
                return null;
            }
        }
        return null;
    }

    private List<Fee> getFeeByMember(Map map) {

        List<Fee> feeList = new ArrayList<>();

        Map<String, Object> uniBssBody = (Map<String, Object>) map.get("UNI_BSS_BODY");
        if (KiteMapUtils.isEmpty(uniBssBody)) {
            return null;
        }
        Map<String, Object> rsp = (Map<String, Object>) uniBssBody.get("RSP");
        if (!KiteStringUtils.equals(KiteMapUtils.getString(rsp, "RESP_CODE"), "0000")) {
            return null;
        }
        List<Map<String, Object>> userDiscntInfos = (List<Map<String, Object>>) rsp.get("USER_DISCNT_INFOS");
        if (KiteListUtils.isEmpty(userDiscntInfos)) {
            return null;
        }

        if (KiteListUtils.isNotEmpty(userDiscntInfos)) {
            userDiscntInfos.forEach(userDiscntInfoMap -> {
                Fee fee = new Fee();
                fee.setFeeCode(KiteMapUtils.getString(userDiscntInfoMap, "DISCNT_CODE"));
                // 资费名称
                String feeName = "";
                String feeDesc = "详情";
                String discntProductId = KiteMapUtils.getString(userDiscntInfoMap, "DISCNT_PRODUCT_ID");
                if (KiteStringUtils.isNotEmpty(discntProductId)) {
                    Offer additionalOffer = OfferCache.get(discntProductId);
                    if (additionalOffer != null) {
                        feeName = additionalOffer.getOfferName();
                    }
                }
                fee.setFeeName(feeName);
                fee.setFeeDesc(feeDesc);

                //资费属性
                List<Map<String, Object>> userDiscntItemInfos = (List<Map<String, Object>>) userDiscntInfoMap.get("USER_DISCNT_ITEM_INFOS");
                if (KiteListUtils.isNotEmpty(userDiscntItemInfos)) {
                    Map<String, String> attrMap = GetFeeInfoTask.getAttrMap(userDiscntItemInfos);
                    fee.setAttrMap(attrMap);
                }

                //处理资费时间
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                String startDate = KiteMapUtils.getString(userDiscntInfoMap, "START_DATE");
                String endDate = KiteMapUtils.getString(userDiscntInfoMap, "END_DATE");
                Date start = null;
                Date end = null;
                try {
                    start = simpleDateFormat.parse(startDate);
                    end = simpleDateFormat.parse(endDate);
                } catch (ParseException e) {
                    LOGGER.error(ErrorConsts.SYSTEM_ERROR.getErrorCode(), e, "格式化时间失败");
                    ErrorConsts.BUSI_COMMON_ERROR.throwOut("格式化时间失败");
                }

                if (end != null && start != null) {
                    fee.setStartDate(KiteDateUtils.formatDate(start, "yyyy-MM-dd"));
                    fee.setEndDate(KiteDateUtils.formatDate(end, "yyyy-MM-dd"));
                    feeList.add(fee);
                }
            });
        }

        return feeList;
    }
}
